
Classes and Objects in JS
Classes and objects are a fundamental concept in object-oriented programming (OOP). In JavaScript, classes and objects are used to create reusable code and promote modularity. In this article, we will explore the basics of classes and objects in JavaScript.
What is an Object?
An object is an instance of a class. It has its own set of attributes (data) and methods (functions) that can be used to interact with the object. Objects are the basic building blocks of OOP's, and they are used to model real-world objects and their interactions.
What is a Class?
A class is a blueprint or a template that defines the properties and methods of an object. It is a way to define a set of attributes and methods that can be used to create objects. Classes are the foundation of OOP's, and they are used to model real-world objects and their interactions.
class RailwayForm{
submit(){
alert(this.name + " Form Submitted" + " for this Train no." + this.trainNo);
}
cancel(){
alert(this.name + " Form Cancelled" + " for this Train no." + this.trainNo);
}
fill(givenname, trainno){
this.name = givenname;
this.trainNo = trainno
}
}
let rohanForm = new RailwayForm()
rohanForm.fill("Rohan", 12210)
let mohanForm1 = new RailwayForm()
let mohanForm2 = new RailwayForm()
mohanForm1.fill("Mohan", 11110)
mohanForm2.fill("Mohan", 1213340)
mohanForm1.submit()
rohanForm.submit()
mohanForm2.submit()
mohanForm1.cancel()Code Overview
This code defines a class called RailwayForm to simulate filling, submitting, and canceling a train reservation form.
Class Declaration:
class RailwayForm {
Method: submit()
submit() {
alert(this.name + " Form Submitted" + " for this Train no." + this.trainNo);
}
Method: cancel()
cancel() {
alert(this.name + " Form Cancelled" + " for this Train no." + this.trainNo);
}
Method: fill(givenname, trainno)
fill(givenname, trainno) {
this.name = givenname;
this.trainNo = trainno;
}Creating and Filling Object: rohanForm
let rohanForm = new RailwayForm();
rohanForm.fill("Rohan", 12210);rohanForm.name = "Rohan"
rohanForm.trainNo = 12210
Creating Two Forms for Mohan
let mohanForm1 = new RailwayForm();
let mohanForm2 = new RailwayForm();mohanForm1.fill("Mohan", 11110);
mohanForm2.fill("Mohan", 1213340);